<?php
/*
	Copyright (C) 2008 - 2012 Inanta Martsanto
	Inanta Martsanto (inanta@inationsoft.com)

	This file is part of Koma.

	Koma is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Koma is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Koma.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Inationsoft\Koma;

use Inationsoft\NS\Core\Config;
use Inationsoft\NS\Core\Router;
use Inationsoft\NS\Core\Model;
use Inationsoft\NS\UI\ScriptManager;
use Inationsoft\NS\UI\StyleManager;
use Inationsoft\NS\Template\Template;
use Inationsoft\NS\Exception\PageNotFoundException;
use Inationsoft\NS\Exception\ServiceUnavailableException;

/**
 *Koma main class runtime
 *
 *@author Inanta Martsanto <inanta@inationsoft.com>
 */
final class Koma {
	private $_blocks = array();

	function initialize() {
		$config = Config::getInstance();
		require(NS_SYSTEM_PATH . '/' . $config->ConfigFolder . '/Koma.inc.php');

		$temp_folder = $config->ApplicationFolder;
		$config->ApplicationFolder .= '/system';

		$sm = Model::getInstance('SystemModel');
		$this->_blocks = $sm->getBlock();

		$Koma = array_merge($Koma, $sm->getConfig());
		$Koma['ThemePath'] = NS_SYSTEM_PATH . '/theme/' . $Koma['Theme'];
		$Koma['ThemePublicURL'] = NS_PUBLIC_URL . '/koma/theme/' . $Koma['Theme'];
		$Koma['ThemeMainTemplate'] = 'theme.php';
		$Koma['Application'] = '';

		$config->Application->DebugMode = (bool)$Koma['Debug'];
		unset($Koma['Debug']);

		$config->add(array('Koma' => $Koma));
		$config->ApplicationFolder = $temp_folder;

		$app_folder = '';

		if($pos = strpos($_SERVER['PHP_SELF'], 'index.php/')) $app_folder = current(explode('/', (substr($_SERVER['PHP_SELF'] . '/', $pos + 10)), 2));
		if($app_folder == '') $app_folder = $config->Koma->DefaultModule;

		$app_config = $sm->getApp($app_folder);
		if(!$app_config || !$app_config['is_enabled']) throw new PageNotFoundException();

		$config->ApplicationFolder .= '/' . $app_folder;
		$config->Koma->Application = $app_folder;

		if($handle = opendir(NS_SYSTEM_PATH . '/' . $config->ApplicationFolder . '/controllers')) {
			while(false !== ($entry = readdir($handle))) {
				if(strtolower($app_folder . '.php') === strtolower($entry)) {
					$app_folder = '';
					break;
				}
			}

			closedir($handle);
		}

		if($app_folder != '') {
			$_SERVER['PHP_SELF'] = str_replace($app_folder . '/', '', $_SERVER['PHP_SELF']);

			if(isset($_SERVER['PATH_INFO'])) $_SERVER['PATH_INFO'] = str_replace($app_folder . '/', '', $_SERVER['PATH_INFO']);
			else if(isset($_SERVER['ORIG_PATH_INFO'])) $_SERVER['ORIG_PATH_INFO'] = str_replace($app_folder . '/', '', $_SERVER['ORIG_PATH_INFO']);
		}
	}

	function prepare() {
		$router = Router::getInstance();
		$router->App->_createProperty('Folder', Config::getInstance()->Koma->Application);
		if(get_parent_class($router->App) == 'Inationsoft\Koma\BlockController') throw new PageNotFoundException();
	}

	function run() {
		$router = Router::getInstance();
		$config = Config::getInstance();

		if(!$router->App->Session->get('SessionToken')) $router->App->Session->set('SessionToken', md5(session_id() . $config->Application->Salt));
		if($config->Koma->ThemeMainTemplate == null) return;

		$blocks = array();
		$current_app_folder = $config->ApplicationFolder;
		$orig_app_folder = current(explode('/', $config->ApplicationFolder));
		$app_root_path = NS_SYSTEM_PATH . '/' . $orig_app_folder . '/';

		foreach($this->_blocks as $block) {
			if(is_readable($app_root_path . $block['application_path'] . '/controllers/' . $block['block_path'] . '.php')) {
				@include($app_root_path . $block['application_path'] . '/controllers/' . $block['block_path'] . '.php');

				$config->ApplicationFolder = $orig_app_folder . '/' . $block['application_path'];
				$class = end(explode('/', $block['block_path']));
				$run = new $class;

				$run->Action = 'run';
				$run->Path = NS_SYSTEM_PATH . '/' . $config->ApplicationFolder;
				$run->_run();
				$blocks[$class] = $run->Content;
			}
		}

		$config->ApplicationFolder = $current_app_folder;

		ob_start();

		$js = ScriptManager::getInstance();
		$css = StyleManager::getInstance();

		$user = User::getInstance();
		if((bool)$config->Koma->IsOffline && (!$user->isAdmin() && !defined('KOMA_APP_FORCE_ONLINE'))) throw new ServiceUnavailableException('This site is temporary unvailable');

		$template = Template::getInstance();

		if(is_readable($config->Koma->ThemePath . '/config.php')) {
			include($config->Koma->ThemePath . '/config.php');

			if(is_array($Theme['Script'])) { foreach($Theme['Script'] as $script) { $js->addSource($script); } }
			if(is_array($Theme['Style'])) { foreach($Theme['Style'] as $style) { $css->addExternalSource($style); } }
		}

		$template->assign(array(
			'Koma' => array(
				'Content' => $router->App->Content,
				'Config' => &$config,
				'ScriptManager' => $js,
				'StyleManager' => $css,

				'User' => array('Username' => $user->Username, 'FullName' => $user->FullName, 'Token' => $user->Token),
				'Blocks' => $blocks
			)
		));
		$template->display($config->Koma->ThemePath . '/' . $config->Koma->ThemeMainTemplate);

		$router->App->Content = ob_get_clean();

		ScriptManager::getInstance()->renderToFile(NS_SYSTEM_PATH . '/asset/cache');
		StyleManager::getInstance()->renderToFile(NS_SYSTEM_PATH . '/asset/cache');
	}

	function finalize() { }
}
?>
